<template>
  <n-form-item label="关键字" label-placement="left" :show-feedback="false">
    <n-input v-model:value="searchKey" placeholder="请输入名称搜索" clearable/>
  </n-form-item>
  <n-tree :data="treeData" :node-props="nodeProps"
          :render-label="renderLabel"
          v-model:checked-keys="checkedRows"
          checkable
          block-line
          cascade
          class="slash-tree"
          default-expand-all
          expand-on-dragenter
          key-field="id"
          label-field="label"
          selectable="true"
          :default-checked-keys="checkedRows"
          style="max-height: 600px; min-height: 600px;overflow-y: scroll"


  />
</template>

<script lang="ts">
import {defineComponent, h, onMounted, ref, unref, watch} from "vue";
import {NTooltip, TreeOption} from "naive-ui";
import httpApi from "@/views/AuthTbUser/UserBindDataSecurity/httpApi";
import {string} from "vue-types";
import { debounce } from "lodash";
import { SlashAppContext } from "slash-admin";

export default defineComponent(
    {
      components: {},
      emits: ["select"],
      props: {
        entityName: {
          type: string,
        },
        fieldName: {
          type: string
        },
        checkedIds:{
        }
      },
      setup(props, ctx) {
        const searchKey = ref<String>("")
        const checkedRows = ref([]);
        const treeHeight = `${SlashAppContext.getAppConfig().fontSizeCoefficient * 60}px`;
        /** 备份完整的树数据 */
        const treeDataBackup = ref([]);
        const updateCheckedKeys = (row: any, it: any) => {
          console.log(row, it);
        }
        const renderLabel = (info: { option: Record<string, any> & TreeOption, checked?: boolean, selected?: boolean }) => {
          const {option} = info
          return h(NTooltip, {}, {
            default: option.label,
            trigger: h('div', {
              class: 'ellipsis-text'
            }, option.label)
          })
        }
        const nodeProps = ({option}: { option: TreeOption }) => {
          return {
            onClick() {
              if (option.nodeType == 'obj') {
                ctx.emit("select", option);
              }
            }

          };
        };
        onMounted(() => {
          init();
        });
        const doSubmit = async () => {
          const temp: any[] = findTreeData(checkedRows.value, unref(treeDataBackup));
          const result: any[] = [];
          console.log(temp);

          for (const r of temp) {
            result.push({
              id: r.id,
              label: r.label,
              value: r.value
            })
          }
          return result;
        };
        const findTreeData = (ids: string[], treeData: any[]): any[] => {
          let result: any[] = [];
          for (let i = 0; i < treeData.length; i++) {
            const tree = treeData[i];
            if (ids.find(it => it == tree.id) && tree.id != 0 && tree != '0') {
              result.push(tree);
            }
            if (tree['children']) {
              const temp = findTreeData(ids, tree['children'])
              result = [...result, ...temp];
            }
          }
          return result;
        }
        const reload = async () => {
          await init();
        };
        const treeData = ref<any>([]);
        const init = async () => {
          await loadTreeList(true);
        };
        const loadTreeList = async (isRefresh?: boolean) => {
          const msg = await httpApi.selectDataPermissions({
            searchKey: searchKey.value,
            entityName: props.entityName,
            filterEntity: 1
          } as any);
          treeData.value = [
            {
              id: 0,
              label: "可选数据  ",
              children: [...msg.data],
              disabled: true
            }
          ];
          isRefresh && (checkedRows.value=props.checkedIds as any);
          if (!searchKey.value) {
            treeDataBackup.value = treeData.value;
          }
          console.log(treeData.value);
        }

        watch(
          () => searchKey.value,
          debounce(() => {
            loadTreeList(false);
          }, 200)
        )
        return {
          checkedRows,
          updateCheckedKeys,
          doSubmit,
          searchKey,
          renderLabel,
          treeData,
          nodeProps,
          defaultExpandedKeys: ref(["40", "41"]),
          treeHeight
        };
      }
    }
);


</script>

<style lang="less" scoped>

.slash-tree {
  height: calc(100% - v-bind(treeHeight));
  max-height: auto !important;
  min-height: auto !important;
  ::v-deep(.n-tree-node) {
    .n-tree-node-content__suffix {
      visibility: hidden;
    }

    &:hover {
      .n-tree-node-content__suffix {
        visibility: visible;
      }
    }
  }

}

:deep(.n-tree-node-content) {
  .n-tree-node-content__text {
    width: calc(100% - 90px);
  }

  .ellipsis-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin: 0;
  }
}
</style>
